package kr.hkit.androidcomplete02.ch12;

import java.util.ArrayList;

import kr.hkit.androidcomplete02.R;
import android.app.Activity;
import android.os.Bundle;
import android.util.SparseBooleanArray;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

public class ListViewAddDelMultiple extends Activity {
	ArrayList<String> arrItems;
	ArrayAdapter<String> adapter;
	ListView listView;
	EditText et;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ch12_listviewadddel);
		
		et = (EditText) findViewById(R.id.ch12_edit_newitem);

		arrItems = new ArrayList<>();
		arrItems.add("First");
		arrItems.add("Second");
		arrItems.add("Third");
		arrItems.add("Fourth");
		arrItems.add("Fifth");

		adapter = new ArrayAdapter<>(this,
				android.R.layout.simple_list_item_multiple_choice, arrItems);
		
		listView = (ListView) findViewById(R.id.ch12_listview_adddel);
		listView.setAdapter(adapter);
		listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
		listView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				String text = "Select Item = " + arrItems.get(position);
				Toast.makeText(getApplication(), text, Toast.LENGTH_SHORT).show();
			}
		});
	}
	
	public void mOnClick(View v){
		switch(v.getId()){
		case R.id.ch12_btn_add:
			String text = et.getText().toString();
			arrItems.add(text);
			et.setText("");
			adapter.notifyDataSetChanged();
			break;
		case R.id.ch12_btn_del:
			SparseBooleanArray sb = listView.getCheckedItemPositions();
			
			if(sb.size() !=0){
				for(int i=listView.getCount()-1; i>-1; i--){
					if(sb.get(i)){
						arrItems.remove(i);
					}
				}
				listView.clearChoices();
				adapter.notifyDataSetChanged();
			}
			break;
		}
	}
	
}
